﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;
using Top.Api.Request;
using Top.Api.Response;
using System.Web.Security;
using Top.Api;
using System.ComponentModel;
using Top.Api.Domain;
using System.Threading;

namespace AscentExplorer.Web.Areas.Top.Controllers
{
    public class HomeController : Controller
    {
        const string serverUrl = "http://gw.api.taobao.com/router/rest";
        const string appKey = "12344956";
        const string appSecret = "3865429228e6ffd6fb132510ed91c2d7";
        //
        // GET: /Top/Home/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Test()
        {
            return View();
        }

        #region 认证相关
        public RedirectToRouteResult LogOn()
        {
            return RedirectToAction("authorize", "home");
        }

        public RedirectResult Authorize()
        {
            const string authorize_url = "https://oauth.taobao.com/authorize";
            const string response_type = "code";
            string redirect_uri = string.Format("{0}{1}", "http://www.5content.com/", "top/home/token");
            string state = string.Empty;

            string url = string.Format("{0}?response_type={1}&client_id={2}&redirect_uri={3}&state={4}", authorize_url, response_type, appKey, redirect_uri, state);
            return Redirect(url);
        }

        public RedirectToRouteResult Token(string code, string state)
        {
            const string grant_type = "authorization_code";
            //string code;
            string redirect_uri = string.Format("{0}{1}", "http://www.5content.com/", "top/home");
            string queryString = string.Format("grant_type={0}&code={1}&redirect_uri={2}&client_id={3}&client_secret={4}", grant_type, code, redirect_uri, appKey, appSecret);

            string accessToken;
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://oauth.taobao.com/");
                string requestUri = "token?" + queryString;
                accessToken = client.Post(requestUri, null).Content.ReadAsString();
                string sessionKey = accessToken.Split(',')[2].Split(':')[1].Replace("\"", "").Replace("}", "").Trim();
                UserGetRequest request = new UserGetRequest() { Fields = "user_id,uid,nick,sex,buyer_credit,seller_credit,location,created,last_visit,birthday,type,status,alipay_no,alipay_account,alipay_account,email,consumer_protection,alipay_bind" };
                UserGetResponse response = DoExecute(request, sessionKey, DateTime.Now);
                //如果当前登录用户不在我们系统，就建立用户----并且将一些特殊信息写到 comment 中--注意，为了避免重复，这里是将用户的email作为用户名的
                MembershipUser user = Membership.GetUser(response.User.Email);
                if (null == user)
                {
                    user = Membership.CreateUser(response.User.Email, new Guid().ToString(), response.User.Email);
                    if (!Roles.RoleExists("TaobaoUsers"))
                    {
                        Roles.CreateRole("TaobaoUsers");
                    }
                    Roles.AddUserToRole(response.User.Email, "TaobaoUsers");
                }
                user.Comment = string.Format("taobao:{0}:{1}", response.User.Nick, sessionKey);
                Membership.UpdateUser(user);

                FormsAuthentication.SetAuthCookie(response.User.Email, true);
            }

            return RedirectToAction("index", "dashboard");
        }

        [Authorize]
        public RedirectResult Logoff()
        {
            const string logoff_url = "https://oauth.taobao.com/logoff";
            const string redirect_uri = "http://www.5content.com/top/home";

            //先从本系统退出
            FormsAuthentication.SignOut();
            string url = string.Format("{0}?client_id={1}&redirect_uri={2}", logoff_url, appKey, redirect_uri);
            return Redirect(url);
        }

        private static T DoExecute<T>(ITopRequest<T> request, string session, DateTime timestamp) where T : TopResponse
        {
            ITopClient client = new DefaultTopClient(serverUrl, appKey, appSecret);
            return client.Execute(request, session, timestamp);
        }
        #endregion

    }
}
